package main

import (
	"bufio"
	"context"
	"fmt"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"io"
	"log"
	"os"
	"server_stream_server/proto"
)

func main() {
	conn, err := grpc.Dial("127.0.0.1:7070", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatal("连接失败:", err)
		return
	}
	defer conn.Close()

	// 建立连接
	client := proto.NewFileServiceClient(conn)
	// 执行rpc调用
	serverStream, err := client.DownLoad(context.Background(), &proto.FileRequest{Name: "hello.zip"})
	if err != nil {
		log.Fatalln("获取流出错", err)
	}

	file, err := os.OpenFile("winutils-master-new.zip", os.O_CREATE|os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	writer := bufio.NewWriter(file)

	for {
		resp, err := serverStream.Recv()
		if err != nil {
			if err == io.EOF {
				fmt.Println("客户端数据接收完成")
				err := serverStream.CloseSend()
				if err != nil {
					log.Fatal(err)
				}
				break
			}
		}
		writer.Write(resp.Content)
	}
	writer.Flush()
}
